//
//  CinemaViewController.m
//  代号：47
//
//  Created by 杨佩璋 on 15/6/30.
//  Copyright (c) 2015年 杨佩璋. All rights reserved.
//

#import "CinemaViewController.h"
#import "SetupView.h"
#import "AboutUsViewController.h"
#import "VersionViewController.h"
#import <SDImageCache.h>

@interface CinemaViewController (){
    
    NSInteger _flag;
    float _totalCacheSize;
}

@property (nonatomic ,retain)SetupView *setupView;//设置界面


@end
@implementation CinemaViewController


-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    [_setupView removeFromSuperview];
    _flag = 0;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor purpleColor];
    _flag = 0;
    _setupView = [[SetupView alloc] initWithFrame:CGRectMake(0, 64, kScreen_width, kScreen_height - 64 - 49)];
    
    // Do any additional setup after loading the view.

    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Icon-Small"] style:(UIBarButtonItemStylePlain) target:self action:@selector(handleSetupBtnAction:)];
    [self.navigationItem.rightBarButtonItem setWidth:50];
    self.navigationItem.rightBarButtonItem = item1;
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor orangeColor];
    
    [_setupView.clearBtn addTarget:self action:@selector(handleSetupBtnActions:) forControlEvents:UIControlEventTouchUpInside];
    [_setupView.adviceBtn addTarget:self action:@selector(handleSetupBtnActions:) forControlEvents:UIControlEventTouchUpInside];
    [_setupView.aboutBtn addTarget:self action:@selector(handleSetupBtnActions:) forControlEvents:UIControlEventTouchUpInside];
    [_setupView.versionBtn addTarget:self action:@selector(handleSetupBtnActions:) forControlEvents:UIControlEventTouchUpInside];

    // Do any additional setup after loading the view.
//    
}
- (void)handleSetupBtnAction:(UIButton *)btn{
    

//    [UIView transitionFromView:self.view toView:setupVc.view duration:0.5 options:(UIViewAnimationOptionTransitionCrossDissolve) completion:^(BOOL finished) {
//        [setupVc.setupView.buttons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//            AmazingButton *button = obj;
//            [button show];
//        }];
//    }];
    
    if (_flag == 0) {
        [self.navigationController.view addSubview:_setupView];
        [_setupView.buttons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            AmazingButton *button = obj;
            [button show];
            _flag = 1;
        }];
    }else if (_flag == 1){
        
        [_setupView removeFromSuperview];
        _flag = 0;
    }
}
- (void)handleSetupBtnActions:(AmazingButton *)button{
    _flag = 0;[_setupView removeFromSuperview];
    if (button == _setupView.clearBtn) {
        
//        [[SDImageCache sharedImageCache] clearDisk];
//        [[SDImageCache sharedImageCache] clearMemory];
        dispatch_async(
                       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                       , ^{
                           NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                           _totalCacheSize = [self folderSizeAtPath:cachPath];
                           NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                           //                           NSLog(@"files :%ld",[files count]);
                           for (NSString *p in files) {
                               NSError *error;
                               NSString *path = [cachPath stringByAppendingPathComponent:p];
                               if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                   [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                               }
                           }
                           [self showAlertViewWithClear];
                       });
        
        
        
    }
    if (button == _setupView.adviceBtn) {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"mailto://568888047@qq.com"]];
//        NSString *stringURL = @"mailto:test@example.com";
//        NSURL *url = [NSURL URLWithString:stringURL];
//        [[UIApplication sharedApplication] openURL:url];
//        [[UIApplication sharedApplication]openURL:[NSURL   URLWithString:@"http://www.baidu.com"]];
//        NSLog(@" %d ... %s ... %@",__LINE__,__FUNCTION__,@"adviceBtn");
    }
    if (button == _setupView.aboutBtn) {
        
        AboutUsViewController *aboutUs = [[AboutUsViewController alloc] init];
        [self.navigationController pushViewController:aboutUs animated:YES];
        [aboutUs release];
    
    }
    if (button == _setupView.versionBtn) {

        VersionViewController *version = [[VersionViewController alloc] init];
        [self.navigationController pushViewController:version animated:YES];
        [version release];

    }
    
}

//清除缓存的弹框
- (void)showAlertViewWithClear{
    NSString *infoStr = [NSString stringWithFormat:@"成功清除缓存(%.1fM)",_totalCacheSize * 0.2];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除缓存" message:infoStr preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *okbtn = [UIAlertAction actionWithTitle:@"OK" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        
    }];
    [alertController addAction:okbtn];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark  ====遍历文件夹获得文件夹大小，返回多少M
//单个文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
//    NSLog(@" %d ... %s ... %f",__LINE__,__FUNCTION__,folderSize/(1024.0*1024.0));
    return folderSize/(1024.0*1024.0);
}


//先判断——setupView是不是存在  ，   要是存在的话，点击屏幕是setupView消失
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    
    
    
    
}

@end
